package com.dhh.toodledo.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.dhh.toodledo.R;
import com.dhh.toodledo.exception.InValidAccountException;
import com.dhh.toodledo.manager.TaskManager;
import com.dhh.toodledo.model.Task;
import com.dhh.toodledo.util.AuthUtil;
import com.dhh.toodledo.util.CUtil;
import com.dhh.toodledo.util.HttpUtil;
import com.dhh.toodledo.widget.AmazingAdapter;
import com.flurry.android.FlurryAgent;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.LoaderActionBarItem;
import greendroid.widget.QuickAction;
import greendroid.widget.QuickActionGrid;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

public class ShowAllTaksActivity extends GDActivity implements View.OnClickListener{
	private ProgressDialog progressDialog;
	private AuthUtil au;
	private SharedPreferences sp;
	private com.dhh.toodledo.widget.AmazingListView lsComposer;
	private TaskManager tManager;
	private List<Task> initData;
	private SectionComposerAdapter adapter;
    private QuickActionWidget mGrid;
    private Button cDone;
    private Button cStar;
    private Task cTask;
    private String cTaskId;
    private String showType = "all";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.list_tasks);
        tManager = new TaskManager();
        sp = getSharedPreferences("myPre", 0);
        au = new AuthUtil(sp);
        initView();
        if(getIntent().getExtras()!=null){
        	showType = getIntent().getExtras().getString("showType"); 
        }   
        initActionBar(); 	
    }
	
	@Override
    public void onStart(){
       super.onStart();
       FlurryAgent.onStartSession(this, "2ND7X5T2HQCRXGXJ1BUF");
    }
    
    @Override
    public void onStop(){
       super.onStop();
       FlurryAgent.onEndSession(this);
    }
	
	@Override
	public void onResume(){
		super.onResume();
		ShowAllTaksActivity.this.findViewById(R.id.td_loading).setVisibility(View.VISIBLE);
		(new SearchThread()).start();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 0, 0, "View Task");
		menu.add(0, 1, 0, "Delete Task");
		cTaskId = ((TextView) v.findViewById(R.id.ti_checkbox_id)).getText().toString();
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if(item.getItemId()==0){
			Intent intent = new Intent(ShowAllTaksActivity.this,ShowTaskDetailActivity.class);
			intent.putExtra("taskId", cTaskId);
			this.startActivity(intent);
		}else if(item.getItemId()==1){
			showDialog(0);
			new DeleteTask().doInBackground(new String[]{});
		}
		
		return true;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
			case 0:
				progressDialog = new ProgressDialog(this);
				progressDialog.setTitle("Deleting Task ....");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				return progressDialog;			
		}
		
		return null;		
	}
	
	public void initActionBar(){
		if("hotlist".equals(showType)){
			getActionBar().setTitle("Hotlist");
		}else if("star".equals(showType)){
			getActionBar().setTitle("Starred");
		}else if("complete".equals(showType)){
			getActionBar().setTitle("Recently Completed");
		}else{
			getActionBar().setTitle("All Tasks");
		}
		getActionBar().setGravity(Gravity.CENTER_HORIZONTAL);
        getActionBar().setBackgroundColor(Color.rgb(9, 135, 205));
        addActionBarItem(Type.Refresh, R.id.action_bar_refresh);
        addActionBarItem(Type.Add, R.id.action_bar_home_add);
        getActionBar().getChildAt(0).
    	setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ShowAllTaksActivity.this,TDAActivity.class);
				startActivity(intent);
			}});
	}
	
	
	@Override
    public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		switch (item.getItemId()) {
		case R.id.action_bar_refresh:
			ShowAllTaksActivity.this.findViewById(R.id.td_loading).setVisibility(View.VISIBLE);
			(new SearchThread()).start();
            break;
		case R.id.action_bar_home_add:
			Intent intent = new Intent(ShowAllTaksActivity.this,AddTaskActivity.class);
			this.startActivity(intent);
            break;
		}
		
		return true;
	}
	
	private void initView(){
    	lsComposer = (com.dhh.toodledo.widget.AmazingListView) findViewById(R.id.at_lst);  
    	lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				Intent intent = new Intent(ShowAllTaksActivity.this,ShowTaskDetailActivity.class);
				intent.putExtra("taskId", ((TextView)view.findViewById(R.id.tli_task_lst_id)).getText().toString());
				ShowAllTaksActivity.this.startActivity(intent);
			}
		});
		
		lsComposer.setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
				cTaskId = ((TextView)view.findViewById(R.id.tli_task_lst_id)).getText().toString();
				cTask = getTask(Long.valueOf(cTaskId));
				cDone = (Button) view.findViewById(R.id.ti_checkbox);
				cStar = (Button) view.findViewById(R.id.ti_star);
		        prepareQuickActionGrid();
				mGrid.show(view);
				return true;
			}});
		
    }
    
    private void displaySearchResults(){
		adapter = new SectionComposerAdapter();
		lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
		lsComposer.setDivider( null );
		lsComposer.setAdapter(adapter);
		refreshList();
	}
    
    public void refreshList(){
		adapter.reset();
		
		if(adapter.getCount()==0){
			lsComposer.setVisibility(View.GONE);
		}else{
			lsComposer.setVisibility(View.VISIBLE);
			adapter.resetPage();
			adapter.notifyMayHaveMorePages();
		}		
	}
    
    private Handler eHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Intent intent = new Intent(ShowAllTaksActivity.this,LoginActivity.class);
        	ShowAllTaksActivity.this.startActivity(intent);
        }
    };
    
    private Handler nHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Intent intent = new Intent(ShowAllTaksActivity.this,TDAActivity.class);
        	ShowAllTaksActivity.this.startActivity(intent);
        }
    };
    
    private class SearchThread extends Thread {
        @Override
        public void run() {  
        	refresh();   	
        }        
    }
    
    private void refresh(){
    	try{
    		Calendar c = Calendar.getInstance();
    		c.set(Calendar.HOUR, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
    		int todayTime = Integer.valueOf(CUtil.getStamp(c.getTime()));		
    		c.setTimeInMillis(c.getTimeInMillis() + 24*3600*1000);
    		int tomTime = Integer.valueOf(CUtil.getStamp(c.getTime()));		
    		c.setTimeInMillis(c.getTimeInMillis() + 24*3600*1000);
    		int tomTime2 = Integer.valueOf(CUtil.getStamp(c.getTime()));		
    		c.setTimeInMillis(c.getTimeInMillis() + 6*24*3600*1000);
    		int next7 = Integer.valueOf(CUtil.getStamp(c.getTime()));
    		
        	if("overdue".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()>0&& t.getDuedate()<todayTime){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("today".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()<tomTime&& t.getDuedate()>=todayTime){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("tomorrow".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()<tomTime2&& t.getDuedate()>=tomTime){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("next7".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()<next7&& t.getDuedate()>=todayTime){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("later".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()>=next7&& t.getDuedate()>=todayTime){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("nodue".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getDuedate()==0){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("negative".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getPriority()==-1){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("low".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getPriority()==0){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("medium".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getPriority()==1){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("high".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getPriority()==2){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("top".equals(showType)){
        		List<Task> tasks = HttpUtil.getAllTasks(au.getKeyValue());
        		List<Task> tmp = new ArrayList<Task>();
        		for(Task t : tasks){
        			if(t.getPriority()==3){
        				tmp.add(t);
        			}
        		}
        		initData = tmp;        		
        	}else if("star".equals(showType)){
        		initData = HttpUtil.getAllTasks(au.getKeyValue(),"1");      		
        	}else if("complete".equals(showType)){
        		initData = HttpUtil.getTaskComp(au.getKeyValue());      		
        	}else if("hotlist".equals(showType)){
        		initData = HttpUtil.getHotTasks(au.getKeyValue(),sp.getInt("hotlistduedate", 0),sp.getInt("hotlistpriority", 0),sp.getInt("hotliststatus", 0),sp.getInt("hotliststar", 1));      		
        	}else{
        		initData = tManager.getTasks(au.getKeyValue(),String.valueOf(0)).second;
        	}
        	handler.sendEmptyMessage(0);
    	}catch(InValidAccountException e){
    		eHandler.sendEmptyMessage(0);
    	}catch(Exception e){
    		nHandler.sendEmptyMessage(0);
    	}   
    }
        
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	displaySearchResults();
        	ShowAllTaksActivity.this.findViewById(R.id.td_loading).setVisibility(View.GONE);
        	LoaderActionBarItem loaderItem = (LoaderActionBarItem) ShowAllTaksActivity.this.getActionBar().getItem(0);
        	loaderItem.setLoading(false);
        }
    };
    
    private Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {        	
        	if(cDone!=null){
        		if(cTask.getCompleted()>0)
        			cDone.setBackgroundResource(R.drawable.ic_checkbox_full);
        		else
        			cDone.setBackgroundResource(R.drawable.ic_checkbox_empty);
        	}
        	cDone = null;
        	
        	if(cStar!=null){
        		if(cTask.getStar()==0)
        			cStar.setBackgroundResource(android.R.drawable.star_big_off);
        		else
        			cStar.setBackgroundResource(android.R.drawable.star_big_on);
        	}
        	cStar = null;
        	
        	updateTask(cTask);
        	cTask = null;
        }
    };
    
    private void prepareQuickActionGrid() {
        mGrid = new QuickActionGrid(this);                
        mGrid.addQuickAction(new QuickAction(
        				this, 
        				cTask.getCompleted()==0?R.drawable.ic_checkbox_full:R.drawable.ic_checkbox_empty, 
        				cTask.getCompleted()==0?R.string.mark_done:R.string.mark_undone));
        mGrid.addQuickAction(new QuickAction(
        				this, 
        				cTask.getStar()==0?android.R.drawable.star_big_on:android.R.drawable.star_big_off, 
        				cTask.getStar()==0?R.string.mark_start:R.string.mark_unstart));
        mGrid.addQuickAction(new QuickAction(this, R.drawable.ic_delete, R.string.mark_start));

        mGrid.setOnQuickActionClickListener(mActionListener);
    }
	
	public void onShowGrid(View v) {
        mGrid.show(v);
    }
	
	private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
        public void onQuickActionClicked(QuickActionWidget widget, int position) {
        	if(position==0){    			
    			if(cTask.getCompleted()>0)
        			cDone.setBackgroundResource(R.drawable.ic_checkbox_empty);
        		else
        			cDone.setBackgroundResource(R.drawable.ic_checkbox_full);
    			
    			String cmd = "";
    			if(cTask.getCompleted()==0) 
    				cmd = "completed";
    			
    			new UpdateTask().execute(new String[]{"done",String.valueOf(cTask.getId()),cmd});
        	}else if(position==1){
    			if(cTask.getStar()==0)
    				cStar.setBackgroundResource(android.R.drawable.star_big_on);
        		else
        			cStar.setBackgroundResource(android.R.drawable.star_big_off);
    			
    			String cmd = "";
    			if(cTask.getStar()==0)
    				cmd = "star";
    			new UpdateTask().execute(new String[]{"star",String.valueOf(cTask.getId()),cmd});
        	}else if(position==2){
        		showDialog(0);
    			new DeleteTask().doInBackground(new String[]{});
        	}
        }
    };	 
    
    class SectionComposerAdapter extends AmazingAdapter {
		private AsyncTask<Integer, Void, Pair<Boolean, List<Task>>> backgroundTask;
		private List<Task> list = new ArrayList<Task>();	
		
		public void reset() {
			if (backgroundTask != null) backgroundTask.cancel(false);
			
			list = initData;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Task getItem(int position) {
			return list.get(position);
		}
		
		public void removeTask(Long taskId){
			for(int i=0; i<list.size(); i++){
				Task t = list.get(i);
				if(t.getId().longValue()==taskId.longValue()){
					list.remove(i);
					break;
				}
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {			
			if (backgroundTask != null) {
				backgroundTask.cancel(false);
			}
			
			backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Task>>>() {
				@Override
				protected Pair<Boolean, List<Task>> doInBackground(Integer... params) {
					int page = params[0];			
					if("all".equals(showType)){
						try{
							return tManager.getTasks(au.getKeyValue(),String.valueOf((page-1)*25));
						}catch(InValidAccountException e){
			        		eHandler.sendEmptyMessage(0);
			        		return new Pair<Boolean, List<Task>>(false,null);
			        	}catch(Exception e){
			        		return new Pair<Boolean, List<Task>>(false,null);
			        	}     
						
					}else{
						return new Pair<Boolean, List<Task>>(false,null);
					}
				}
				
				@Override
				protected void onPostExecute(Pair<Boolean, List<Task>> result) {
					if (isCancelled()) return; 
					
					if(!"all".equals(showType)) {
						notifyNoMorePages();
						return;
					}
					
					list.addAll(result.second);
					nextPage();
					notifyDataSetChanged();
					
					if (result.first) {
						notifyMayHaveMorePages();
					} else {
						notifyNoMorePages();
					}
				};
			}.execute(page);
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			Task item = getItem(position);
			
			if (res == null) res = getLayoutInflater().inflate(R.layout.task_list_item, null);
			//registerForContextMenu(res);
			Button done = (Button) res.findViewById(R.id.ti_checkbox);
			((TextView) res.findViewById(R.id.ti_checkbox_id)).setText(item.getId().toString());
			TextView title = (TextView) res.findViewById(R.id.ti_title);
			TextView date = (TextView) res.findViewById(R.id.ti_date);
			TextView priority = (TextView) res.findViewById(R.id.ti_priority);
			Button star = (Button) res.findViewById(R.id.ti_star);
			((TextView) res.findViewById(R.id.ti_star_id)).setText(item.getId().toString());
			((TextView) res.findViewById(R.id.tli_task_lst_id)).setText(item.getId().toString());	
			
			title.setText(item.getTitle());
			date.setText(item.getDuedateTitle(sp.getInt("dateformat", 0)));
			priority.setText(item.getPriorityTitle());
			if(item.getStar()==1){
				star.setBackgroundResource(android.R.drawable.star_big_on);
	    	}else{
	    		star.setBackgroundResource(android.R.drawable.star_big_off);
	    	}
			if(item.getCompleted()>0){
	    		done.setBackgroundResource(R.drawable.ic_checkbox_full);
	    	}else{
	    		done.setBackgroundResource(R.drawable.ic_checkbox_empty);
	    	}
			
			return res;
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
		}

		@Override
		public int getPositionForSection(int section) {
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			return 0;
		}

		@Override
		public Object[] getSections() {
			return null;
		}		
	}

	@Override
	public void onClick(View v) {}
	
	private class UpdateTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			Task task = new Task();
			try{
				if("done".equals(params[0])){
					task = tManager.markDone(au.getKeyValue(),Long.valueOf(params[1]), params[2].equals("completed"));
				}else if("star".equals(params[0])){
					task = tManager.markStar(au.getKeyValue(),Long.valueOf(params[1]), Long.valueOf(params[2].equals("star")?1:0));
				}
				
				if(task!=null)
					cTask = task;
				
				updateHandler.sendEmptyMessage(0);
			}catch(InValidAccountException e){
        		eHandler.sendEmptyMessage(0);
        	} 
			
			return "All Done!";
		}
	}
	
	private Task getTask(Long id){
		for(int i=0; i<adapter.getCount(); i++){
			if(adapter.getItem(i).getId().longValue()==id.longValue())
				return adapter.getItem(i);
		}
		return null;
	}
	
	private void updateTask(Task task){
		for(int i=0; i<adapter.getCount(); i++){
			if(adapter.getItem(i).getId().longValue()==task.getId().longValue())
				adapter.getItem(i).setCompleted(task.getCompleted());
				adapter.getItem(i).setStar(task.getStar());
		}
	}
	
	private Handler rHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	adapter.removeTask(Long.valueOf(cTaskId));
        	displaySearchResults();
        	progressDialog.dismiss();
        }
    };
	
	private class DeleteTask extends AsyncTask<String, Integer, String> {
		@Override
		protected String doInBackground(String... params) {
			try {
				tManager.deleteTask(au.getKeyValue(),Long.valueOf(cTaskId));
				rHandler.sendEmptyMessage(0);
			} catch (InValidAccountException e) {
				eHandler.sendEmptyMessage(0);
			}
			
			return "All Done!";
		}
	}

}
